#稀疏图

class SparseGraph:
    def __init__(self, n, directed=False):
        self.n = n  #顶点vertex
        self.m = 0  #边edge
        self.directed = directed #有向
        self.graph = [{} for i in range(n)]

    def __str__(self):
        for index,edge in enumerate(self.graph):
            print(index, edge)
        return ''
        
    def __iter__(self):
        return iter(range(self.m))

    def __getitem__(self, vs):
        if isinstance(vs,tuple) and len(vs)==2:
            return self.graph[vs[0]][vs[1]]
        elif isinstance(vs,int):
            return self.graph[vs]
        else : return

    def __setitem__(self, vs, w):
        if not isinstance(vs,tuple) and len(vs) != 2:
            raise Exception('Two Vertexs needed')
        v1,v2 = vs
        if 0 <= v1 < self.n and 0 <= v2 < self.n:
            if v2 not in self.graph[v1]:
                self.m += 1
            self.graph[v1][v2] = w
            if v1 != v2 and not self.directed :
                self.graph[v2][v1] = w 
        else: raise Exception('Vertex not in the graph')

g=SparseGraph(5)
g[0,3]=43
g[0,4]=32
print(g[0])
print(g[3,0])